<?php
class PictureListControl {
	public function PictureListControl(){
		// no implementation
	}
	
	/**
	 * 
	 * The method will return the rendered component for a list of pictures. The 
	 * list of pictures is provided together with the number of items on a line. 
	 * 
	 * @param unknown_type $number the number of items on a line (let's say 4)
	 * @param unknown_type $pictures the array with pictures
	 */
	public function render($number, $pictures, $selected, $readonly){
		
		$sel = is_array($selected) ? array_flip($selected) : array();
		
		$arr = array();
		$arr[] = '<table cellspacing="0" cellpadding="8" class="pictures">';

		$count = count($pictures); // total number of items
		$lines = (int) ($count / $number); // lines 
		
		if($count % $number > 0){
			$lines ++;
		}
		
		for($i = 0; $i < $lines ; $i++){
			$arr[] = '<tr>';
			
			for($j = 0; $j < $number; $j++){
				$index = $i * $number + $j;
				
				if($index < $count){
					$item = $pictures[$index];
					$id = $item->getId(); // this is the id that will be shown
					
					$class = '';
					if(array_key_exists($id, $sel)){
						$class = ' class="selected"';
					}
					
					$url = 'smallimage.php?id=' . $id;
					$regurl='regimage.php?id=' . $id;
					
					$arr[] = "<td {$class}><a class=\"lightb\" href=\"{$regurl}\"><img src=\"{$url}\" border=\"0\"></a></td>";
				}
				else {
					$arr[] = '<td>&nbsp;</td>';
				}
			}
			
			$arr[] = '</tr><tr>';
			
			for($j = 0; $j < $number; $j++){
				$index = $i * $number + $j;
				
				if($index < $count){
					$item = $pictures[$index];
					$id = $item->getId();
					$class = '';
					$input = '';
					if(array_key_exists($id, $sel)){
						$class = ' selected';
						$input = $id;
					}
					
					$name = htmlspecialchars($item->getComments());
					$field = "<input type=\"hidden\" name=\"selected[]\" value=\"{$input}\">";
					$dummy = "<input type=\"hidden\" name=\"dummy\" value=\"{$id}\">";
					
					
					$editLink = "";
					$selectLink = "";
					$break = "";

					if(! $readonly){
						$editLink = "<a href=\"javascript: triggeredit('{$id}', 'edit')\">edit</a>";
						$selectLink = "<a href=\"javascript: none()\" onclick=\"toggleSelected(event)\">select</a>";
						$break = "<br/>";
					}
					
					$arr[] = "<td class=\"label{$class}\">{$dummy}{$field}
							{$editLink} {$selectLink}{$break}
							<div style='width: 150px;'>{$name}</div></td>";
				}
				else {
					$arr[] = '<td class="label">&nbsp;</td>';
				}
			}
			
			$arr[] = '</tr>';
		} // for
		
		$arr[] = '</table>';
		
		// return the lines produced in the array
		return join(' ', $arr);
	}
	
} 
?>
